from django.shortcuts import render

# Create your views here.
from django.views import View
from meiduo.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
from meiduo.utils.response_code import RETCODE
from random import randint
import logging
from meiduo.libs.yuntongxun.sms import CCP


class ImageCodeView(View):
    '''图形验证码'''

    def get(self, request, uuid):
        # 使用SDK生成图形验证玛
        # name:唯一标识
        # text:图形验证码中的字符内容
        # image_bytes:图片bytes类型数据

        name, text, image_bytes = captcha.generate_captcha()

        # 创建redis连接对象

        redis_conn = get_redis_connection('verify_code')
        # 把图形验证玛字符内容存储到redis中,为了后面发短信用的
        redis_conn.setex(uuid, 300, text)
        # 响应
        return http.HttpResponse(image_bytes, content_type='image/png')


class SHSCodeView(View):
    '''发送短信验证码'''
    def get(self,request,mobile):
        #接收前端数据
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验
        if all(image_code_client,uuid) is False:
            return http.HttpResponseForbidden('缺少必传参数')


        # 创建redis连接对象
        redis_conn = get_redis_connection('verify_code')
        # 获取redis中的图形验证码
        image_code_server = redis_conn.get(uuid)

        # 判断图形验证有没有过期
        if image_code_server is None:

            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图像验证码以过期'})
        # 判断用户输入的图形验证码和redis中之前的验证码一致
        # 从redis获取出来的数据是bytes类型
        if image_code_client.lower() != image_code_server.decode.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码错误'})


        # 随机生成六位数的验证玛
        sms_code = '06d' % randint(0,999999)
        logging.info(sms_code)

        #把短信验证码存储到REDIS中以备后期注册是校验

        redis_conn.setex('sms_code_%s' % mobile,300,sms_code)
        # 利用第三方发短信
        CCP().send_template_sms(mobile,[sms_code,5],1)

        # 响应
        return  http.JsonResponse({'code':RETCODE.OK,'errmsg':"OK"})


